package cn.weekimwee.map3d

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import cn.weekimwee.map3d.wkw.WKWDrivingRouteOverlay
import com.amap.api.maps.AMap
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.maps.utils.SpatialRelationUtil
import com.amap.api.maps.utils.overlay.SmoothMoveMarker
import com.amap.api.services.core.AMapException
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.route.*
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_test.*
import org.jetbrains.anko.toast
import java.util.concurrent.TimeUnit


class TestActivity : AppCompatActivity() {

    private var rOverlay: WKWDrivingRouteOverlay?=null
    private lateinit var aMap: AMap
    private lateinit var smoothMarker: SmoothMoveMarker
    private lateinit var routeSearch: RouteSearch
    private lateinit var disposable:Disposable
    private val startPoint = LatLonPoint(29.859852, 121.586034)//起点 健康城
    private val throughPoint = LatLonPoint(29.852392, 121.580325) //经停点 儿童公园南门
    private val endPoint = LatLonPoint(29.832915, 121.566666)//终点 印象城

    private var latLonArray = arrayListOf<LatLng>()
    private var runArray = arrayListOf<LatLng>()
    private var buttonOnClick = true
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)
        mapView.onCreate(savedInstanceState)
        aMap = mapView.map
        smoothMarker = SmoothMoveMarker(aMap)
        routeSearch = RouteSearch(this).apply {
            calculateDriveRouteAsyn(RouteSearch.DriveRouteQuery(RouteSearch.FromAndTo(startPoint, throughPoint), RouteSearch.DrivingDefault, null, null, ""))
            setRouteSearchListener(object : RouteSearch.OnRouteSearchListener {
                override fun onDriveRouteSearched(p0: DriveRouteResult?, p1: Int) {
                    if (p1 == AMapException.CODE_AMAP_SUCCESS) {
                        if(latLonArray.isNotEmpty()) latLonArray.clear()
                        p0?.paths?.let {
                            it[0].steps.forEach {
                                it.polyline.forEach {
                                    latLonArray.add(LatLng(it.latitude,it.longitude))
                                }
                            }

                            rOverlay = if(buttonOnClick){
                                WKWDrivingRouteOverlay(aMap,latLonArray).apply {
                                    zoomToSpan()
                                }
                            }else{
                                WKWDrivingRouteOverlay(aMap,LatLng(throughPoint.latitude,throughPoint.longitude),LatLng(endPoint.latitude,endPoint.longitude)).apply {
                                    zoomToSpan()
                                }
                            }
                            runArray.apply {
                                add(latLonArray[0])
                                add(latLonArray[1])
                            }
                            showCarMarker()
                        }
                    } else {
                        toast("未规划到数据")
                    }
                }

                override fun onBusRouteSearched(p0: BusRouteResult?, p1: Int) {
                }

                override fun onRideRouteSearched(p0: RideRouteResult?, p1: Int) {
                }

                override fun onWalkRouteSearched(p0: WalkRouteResult?, p1: Int) {
                }

            })
        }
        run.setOnClickListener {
            buttonOnClick = false
            rOverlay?.onDestroy()
            rOverlay = null
            routeSearch.calculateDriveRouteAsyn(RouteSearch.DriveRouteQuery(RouteSearch.FromAndTo(throughPoint, endPoint), RouteSearch.DrivingDefault, null, null, ""))
        }
        start.setOnClickListener {
            if(runArray.isNotEmpty()) runArray.clear()
            //实际上是不停的请求接口  直到数组加载完毕
            disposable = Observable.timer(5, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .repeat()
                    .subscribe({
                        //开始平滑移动
                        if (latLonArray.size >2) {
                            if (runArray.size != 0) {
                                runArray.removeAt(0)
                                runArray.add(latLonArray.removeAt(0))
                            } else{
                                runArray.add(latLonArray.removeAt(0))
                                runArray.add(latLonArray.removeAt(0))
                            }
                            if (smoothMarker != null) smoothMarker.destroy()
                            showCarMarker()
                        }else{
                            disposable?.dispose()
                        }
                    }, {
                        it.printStackTrace()
                    })
        }
    }

    override fun onResume() {
        super.onResume()
        mapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        mapView.onPause()
    }

    override fun onSaveInstanceState(outState: Bundle?) {
        super.onSaveInstanceState(outState)
        mapView.onSaveInstanceState(outState)
    }

    override fun onDestroy() {
        super.onDestroy()
        smoothMarker.destroy()
        rOverlay?.onDestroy()
        mapView.onDestroy()
    }

    private fun showCarMarker(){
        smoothMarker.setDescriptor(BitmapDescriptorFactory.fromResource(R.drawable.icon_car))
        // 取轨迹点的第一个点 作为 平滑移动的启动
        val drivePoint = runArray[0]
        val pair = SpatialRelationUtil.calShortestDistancePoint(runArray, drivePoint)
        runArray[pair.first] = drivePoint
        val subList = runArray.subList(pair.first, runArray.size)
        // 设置轨迹点
        smoothMarker.setPoints(subList)
        // 设置平滑移动的总时间  单位  秒
        smoothMarker.setTotalDuration(5)

        // 设置  自定义的InfoWindow 适配器
        aMap.setInfoWindowAdapter(object : AMap.InfoWindowAdapter {
            override fun getInfoWindow(marker: Marker): View? {
                return null
            }

            override fun getInfoContents(marker: Marker): View? {
                return null
            }
        })
        // 显示 infowindow
        smoothMarker.marker.showInfoWindow()
        smoothMarker.startSmoothMove()
    }
}
